package com.example.appcontact;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.example.adapter.A003DevicesAdapter;
import com.example.adapter.A003DevicesAdapter.OnClickListListener;
import com.example.base.BaseTabActivity;
import com.example.component.QuickAction.OnDismissListener;
import com.example.connect.AsyncTask_Api;
import com.example.connect.AsyncTask_ApiListener;
import com.example.connect.CallApi;
import com.example.connect.ScreenStopper;
import com.example.contact.ContactManager;
import com.example.model.Contacts;
import com.example.model.MyNotifications;
import com.example.model.OutNotifications;
import com.example.model.OutResult;
import com.example.model.Profile;
import com.example.util.ConnectionException;
import com.example.util.EmptyDataException;
import com.example.util.SharedPreferencesDB;
import com.example.util.TokenUnableException;
import com.example.util.Util;
import com.example.util.aes256.SecurityUtils;

public class A003DeviceContact extends BaseTabActivity implements
		AsyncTask_ApiListener, OnDismissListener {
	private static final String TAG = "A003DeviceContact";

	private static final int TYPE_SEND_REQUEST = 33;
	private static final int TYPE_UPDATE_MY_PROFILE = 31;
	private static final int TYPE_GET_MY_PROFILE = 32;
	private static final int TYPE_GET_MY_NOTIFICATIONS = 35;
	private static final int TYPE_GET_LIST_DATA = 12;

	private HashMap<String, Contacts> mapContacts;
	private ListView mListView;
	private A003DevicesAdapter mAdapter;
	private ContactManager mContactManager;
	private int idContactSendRequest;
	private Context mContext;
	private String emailSelected;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initView();
		refresh();
	}

	@Override
	protected void onStart() {
		
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	private void initView() {
		setContentView(R.layout.a003_listview);
		this.mContext = this;
		this.mListView = (ListView) this.findViewById(R.id.a003_listview);
		this.mContactManager = new ContactManager(this);
	}

	private void initData(HashMap<String, Contacts> contact) {
		mapContacts = contact;
		mAdapter = new A003DevicesAdapter(getParent(), R.layout.item_a003,
				Util.convertMapToList(mapContacts), listener);
		mListView.setAdapter(mAdapter);

	}

	private OnClickListListener listener = new OnClickListListener() {

		@Override
		public void onClick(final Contacts data, final int id) {
			if (Util.getNetworkStatus(mContext)) {
				if (data.getStatus() == 0) {
					Util.showDialog(A003DeviceContact.this,
							R.string.request_confirm, R.string.msg_logout,
							R.string.yes, R.string.no,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									emailSelected = data.getEmail();
									idContactSendRequest = id;
									AsyncTask_Api apiTask = new AsyncTask_Api(
											A003DeviceContact.this,
											A003DeviceContact.this,
											TYPE_SEND_REQUEST,
											0,
											ScreenStopper.STYLE_PROGRESS_PROCESS);
									apiTask.execute();
								}
							}, new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});

				}
			}
		}
	};

	private void refresh() {
		if (Util.getNetworkStatus(mContext)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
					TYPE_GET_LIST_DATA, 0, ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}

	@Override
	public Object callApi(int serachType, Object apidata) {
		if (serachType == TYPE_SEND_REQUEST) {
			try {
				String key_md5 = getResources().getString(R.string.md5_key);
				String key_iv = getResources().getString(R.string.iv_key);
				String token = new SharedPreferencesDB(this).getPrefToken();
				final String emailEncrypt = SecurityUtils.encrypt(
						emailSelected, key_iv, key_md5);
				List<String> data = new ArrayList<String>();
				data.add(token);
				data.add(emailEncrypt);
				return CallApi.sendRequest(this, data);

			} catch (Exception e) {
				e.printStackTrace();

			}

		} else if (serachType == TYPE_GET_MY_NOTIFICATIONS) {
			Log.d(TAG, "Start callApi: " + TYPE_GET_MY_NOTIFICATIONS);
			String token = new SharedPreferencesDB(this).getPrefToken();
			List<String> data = new ArrayList<String>();
			data.add(token);
			OutNotifications out = new OutNotifications();
			try{
		        out = (OutNotifications) CallApi.getMyNotifications(this, data);
				}catch (EmptyDataException ex) {
					out.setCode(OutResult.CODE_ERROR_EMPTY);
					out.setMessage(getString(R.string.error_emptydata));
				}catch (TokenUnableException ex) {
					out.setCode(OutResult.CODE_TOKEN);
					out.setMessage(getString(R.string.error_token));
				}catch (ConnectionException ex) {
					out.setCode(OutResult.CODE_ERROR_CONNCECT);
					out.setMessage(getString(R.string.error_connection));
				}catch (Exception ex) {
					out.setCode(OutResult.CODE_ERROR_SYSTEM);
					out.setMessage(getString(R.string.error_system));
				}
			return out;
		} else if (serachType == TYPE_GET_LIST_DATA) {
			SharedPreferencesDB db = new SharedPreferencesDB(mContext);
			return mContactManager.getAllContact(db.getPrefEmail());
		}
		return null;
	}

	@Override
	public void finishApi(int serachType, Object apiresult) {
		// TODO Auto-generated method stub
		if (serachType == TYPE_SEND_REQUEST) {
			OutResult result = (OutResult) apiresult;
			if (result.getStatus()) {
				Toast.makeText(this, "Send request success !",
						Toast.LENGTH_SHORT).show();
				mapContacts.get(emailSelected).setStatus(1);
				mAdapter.notifyDataSetChanged();
				mListView.invalidate();
			} 

		}else if(serachType == TYPE_GET_MY_NOTIFICATIONS){
			if(apiresult != null){
				OutNotifications  my_notifications  = (OutNotifications) apiresult; 
				List<MyNotifications> listMy  = my_notifications.getList();
				if(listMy != null){
					for(MyNotifications to : listMy){
						if(mapContacts.containsKey(to.getEmail())){
							mapContacts.get(to.getEmail()).setStatus(to.getStatus());
						}
					}
					mAdapter.notifyDataSetChanged();
					mListView.invalidate();
				}
				
			}
		} else {
			HashMap<String, Contacts> contact = (HashMap<String, Contacts>) apiresult;
			initData(contact);
			Log.d(TAG, "Call My Notifications !!!");
			callMyNotifications();
		}
	}

	private Contacts isCheckAccountLogin(SharedPreferencesDB db,
			List<Contacts> contact) // TRUE: DA TON TAI --> KIEM TRA CO UDPDATE
									// HAY KHONG? || FALSE: CO THE ADD VAO
									// CONTACT
	{
		try {
			for (Contacts c : contact) {
				if (c != null) {
					Log.e("SON Email", "DB: " + db.getPrefEmail()
							+ " - Email: " + c.getEmail());
					if (db.getPrefEmail().equalsIgnoreCase(c.getEmail()))
						return c;
				}
			}
			return null;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	private void updateContact(Contacts c) {
		if (Util.getNetworkStatus(mContext)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
					TYPE_UPDATE_MY_PROFILE, 0,
					ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}

	private boolean isCheckUpdate(SharedPreferencesDB db, Contacts c) {
		try {
			if (!db.getPrefEmail().equalsIgnoreCase(c.getEmail())
					|| !db.getPrefAddress().equalsIgnoreCase(c.getAddress())
					|| !db.getPrefFirstName()
							.equalsIgnoreCase(c.getFirstName())
					|| !db.getPrefLastName().equalsIgnoreCase(c.getLastName())
					|| !db.getPrefPhone().equalsIgnoreCase(c.getPhoneNumber())
					|| !db.getPrefIdContact().equalsIgnoreCase(c.getId()))
				return true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}

	private HashMap<String, String> createHashMapUpdateProfile(Contacts c) {
		HashMap<String, String> hashMap = null;
		try {
			hashMap = new HashMap<String, String>();

			if (!TextUtils.isEmpty(c.getId()))
				hashMap.put("properties[id_device]", c.getId());
			if (!TextUtils.isEmpty(c.getPhoneNumber()))
				hashMap.put("properties[phone]", c.getPhoneNumber()); // number
			if (!TextUtils.isEmpty(c.getEmail()))
				hashMap.put("properties[email]", c.getEmail()); //
			if (!TextUtils.isEmpty(c.getGender()))
				hashMap.put("properties[gender]", c.getGender()); // -1: none |
																	// 0: famale
																	// | 1: male
			if (!TextUtils.isEmpty(c.getBirthday()))
				hashMap.put("properties[birthday]", c.getBirthday());
			if (!TextUtils.isEmpty(c.getAddress()))
				hashMap.put("properties[address]", c.getAddress());

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (hashMap != null)
				Log.e("SON 005", "HashMap: " + hashMap.toString());
		}
		return hashMap;
	}

	private void getMyProfile() {
		if (Util.getNetworkStatus(this)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
					TYPE_GET_MY_PROFILE, 0,
					ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}

	@Override
	public void onDismiss() {

	}

	@Override
	public void notificationRefresh(List<Contacts> contacts) {
		callMyNotifications();
	}

	@Override
	public void notificationGetNotifi(List<String> email) {
	}

	private void callMyNotifications() {
		if (Util.getNetworkStatus(this)) {
			Log.d(TAG, "Start My Notifications !!!");
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
					TYPE_GET_MY_NOTIFICATIONS, 0,
					ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}

	@Override
	public void tokenExpride() {
		Util.startLogin(getParent());
		
	}
	

}
